class Album < ActiveRecord::Base
  
  ALBUMS_ON_INDEX=4
  ALBUMS_PER_PAGE=20
  validates_presence_of :name, :message => N_("%{fn} can't be empty!")
  validates_uniqueness_of :name 
  
  has_many :photos,:class_name=>'Photo', :dependent=> false
  #选取第一张作为封面相片
  has_one :cover_photo, :class_name=>'Photo', :order=>'created_at ASC'
  
  #返回默认相册
  def self.default_album
    Album.find(:first,:conditions=>["name=?","默认相册"])
  end
  
  #删除前将该相册相片转移到默认相册
  def before_destroy
    
    #TODO:可能存在性能问题，但是可以正确处理默认相册的相片数量
    #self.connection.update "update photos set album_id=#{Album.default_album.id} where album_id=#{self.id}"
    #Album.default_album.photos(:refresh)
    #TODO:可能存在性能问题，但是可以正确处理默认相册的相片数量
    the_default_album=Album.default_album
    self.photos.each do |photo|
      photo.album=the_default_album
      photo.save
    end
    the_default_album.photos(:refresh)
  end
  
  #获取首页显示的相册，当前首页显示4个相册
  def self.albums_on_index
    Album.find(:all,
      :conditions=>["show_on_index=? and is_public=?",true,true],
      :limit=>ALBUMS_ON_INDEX)
  end
  
  #获取所有公开相册分页
  def self.albums_for_public(page)
    Album.paginate(:per_page=>ALBUMS_PER_PAGE, 
      :page=>page, 
      :conditions=>['is_public=?',true],
      :order=>'created_at ASC')
  end
  
  #获取所有相册分页
  def self.paginate_all(page)
    Album.paginate(:per_page=>ALBUMS_PER_PAGE, 
      :page=>page, 
      :order=>'created_at ASC')
  end
  
end
